package com.thermal.thermal_inspection.controller;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.thermal.thermal_inspection.common.CommonResponse;
import com.thermal.thermal_inspection.entity.Inspection;
import com.thermal.thermal_inspection.entity.InspectionData;
import com.thermal.thermal_inspection.entity.InspectionDetail;
import com.thermal.thermal_inspection.entity.InspectionWork;
import com.thermal.thermal_inspection.service.AccountService;
import com.thermal.thermal_inspection.service.CacheService;
import com.thermal.thermal_inspection.service.InspectionService;
import com.thermal.thermal_inspection.vo.*;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/inspection")
public class InspectionController {
    private static final Logger logger = Logger.getLogger(InspectionController.class);

    @Autowired
    InspectionService inspectionService;
    @Autowired
    AccountService accountService;
    @Autowired
    CacheService cacheService;

    //缓存过期时间单位
    static final int timeOut = 10;
    static final TimeUnit timeUnit = TimeUnit.MINUTES;

    /**
     * 新建巡检任务模版
     */
    @PostMapping("/template")
    public CommonResponse<Inspection> addInspectionTemplate(@RequestBody InspectionTemplateVO inspectionTemplateVO){
        int  inspectionMapId = inspectionTemplateVO.getInspectionMapId();
        String inspectionName = inspectionTemplateVO.getInspectionName();
        int inspectionUserId = inspectionTemplateVO.getInspectionUserId();
        int inspectionClassId = inspectionTemplateVO.getInspectionClassId();
        List<InspectionData> inspectionDatas = inspectionTemplateVO.getInspectionDatas();

        //先查看是否存在这个inspectionName，不能重名
        if(inspectionService.existInspectionName(inspectionName)){
            logger.error("新增巡检任务模板失败，巡检任务名已存在，请更换任务名");
            return CommonResponse.createForError("新增巡检任务模板失败，巡检任务名已存在，请更换任务名");
        }

        //然后先新增inspection表，并取出inspection_id
        int rows1 = inspectionService.addInspection(inspectionName, inspectionUserId, inspectionClassId, inspectionMapId);
        if(rows1 == 0){
            logger.error("新增巡检任务模板失败名");
            return CommonResponse.createForError("新增巡检任务模板失败");
        }
        Inspection inspection = inspectionService.getInspectionByName(inspectionName);
        int inspectionId = inspection.getInspectionId();

        //然后用for循环插入inspection_data表
        for(InspectionData inspectionData:inspectionDatas){
            int inspectionGroupId = inspectionData.getInspectionGroupId();
            int mapDetailId = inspectionData.getMapDetailId();
            String inspectionDataDesc = inspectionData.getInspectionDataDesc();
            String inspectionDataName = inspectionData.getInspectionDataName();
            int rows2 = inspectionService.addInspectionData(inspectionId, inspectionGroupId, mapDetailId, inspectionDataDesc, inspectionDataName);
            if(rows2 == 0){
                logger.error("新增巡检任务模板失败名");
                return CommonResponse.createForError("新增巡检任务模板失败");
            }
        }
        logger.info("新增巡检任务模板成功");
        return CommonResponse.createForSuccess("SUCCESS", inspection);
    }
    /**
     * 查看所有任务模版
     */
    @GetMapping("/template")
    public CommonResponse<List<Inspection>> getInspectionTemplate(){
        List<Inspection> inspections = inspectionService.getAllInspectionTemplates();
        if (inspections == null){
            logger.error("获取所有任务模版失败！");
            return CommonResponse.createForError("获取所有任务模版失败！");
        }
        else {
            logger.info("获取所有任务模版成功！");
            return CommonResponse.createForSuccess(inspections);
        }
    }
    /**
     * 查看任务模版的具体详情
     */
    @GetMapping("/template/detail/{inspectionId}/{inspectionMapId}")
    public CommonResponse<List<InspectionDataVO>> getInspectionDetails(@PathVariable("inspectionId") int inspectionId
                                                                    ,@PathVariable("inspectionMapId") int inspectionMapId){
        List<InspectionDataVO> inspectionDataVOS = inspectionService.getAllInspectionDataVOs(inspectionId, inspectionMapId);
        if (inspectionDataVOS == null){
            logger.error("查看任务模版详情出错，有任务模版没有巡检点位！");
            return CommonResponse.createForError("查看任务模版详情出错！请刷新界面再试！");
        }else {
            logger.info("查看任务模版详情成功！");
            return CommonResponse.createForSuccess(inspectionDataVOS);
        }
    }
    /**
     * 分配巡检任务
     */
    @PostMapping("distribute")
    public CommonResponse<InspectionWork> distribute(@RequestBody DistributeVO distributeVO){
        int inspectionLimitTime = distributeVO.getInspectionLimitTime();
        Timestamp inspectionStartTime = distributeVO.getInspectionStartTime();
        String inspectionWorkName = distributeVO.getInspectionWorkName();
        int inspectionId = distributeVO.getInspectionId();
        int inspectionWorkNumber = distributeVO.getInspectionWorkNumber();
        int inspectionWorkStatus = distributeVO.getInspectionWorkStatus();
        List<InspectionDetail> inspectionDetails = distributeVO.getInspectionDetails();

        //先查看是否存在这个inspectionWorkName，不能重名
        if(inspectionService.existInspectionWorkName(inspectionWorkName)){
            logger.error("分配巡检任务失败，分配的巡检任务名已存在，请更换任务名");
            return CommonResponse.createForError("分配巡检任务失败，分配的巡检任务名已存在，请更换任务名");
        }

        //查看分配的模板任务是否存在
        if(!inspectionService.existInspection(inspectionId)){
            logger.error("分配巡检任务失败，模板任务不存在");
            return CommonResponse.createForError("分配巡检任务失败，模板任务不存在");
        }

        //然后先新增inspection_work表，并取出inspection_work_id
        int rows1 = inspectionService.addInspectionWork(inspectionStartTime, inspectionLimitTime, inspectionWorkName,
                inspectionId, inspectionWorkNumber, inspectionWorkStatus);
        if(rows1 == 0){
            logger.error("分配巡检任务失败");
            return CommonResponse.createForError("分配巡检任务失败");
        }
        InspectionWork inspectionWork = inspectionService.getInspectionWorkByName(inspectionWorkName);
        int inspectionWorkId = inspectionWork.getInspectionWorkId();

        //然后用for循环插入inspection_detail表
        for(InspectionDetail inspectionDetail:inspectionDetails){
            int inspectionDetailClass = inspectionDetail.getInspectionDetailClass();
            int inspectionDetailStatus = inspectionDetail.getInspectionDetailStatus();
            int inspectionDetailUser = inspectionDetail.getInspectionDetailUser();
            int inspectionDataId = inspectionDetail.getInspectionDataId();
            String inspectionDetailNote = inspectionDetail.getInspectionDetailNote();
            int rows2 = inspectionService.addInspectionDetail(inspectionWorkId, inspectionDataId, inspectionDetailClass, inspectionDetailUser, inspectionDetailStatus, inspectionDetailNote);
            if(rows2 == 0){
                logger.error("分配巡检任务失败");
                return CommonResponse.createForError("分配巡检任务失败");
            }
        }
        logger.info("分配巡检任务失败分配巡检任务成功");
        return CommonResponse.createForSuccess("SUCCESS", inspectionWork);
    }

    /**
     * 查看分配的巡检任务
     */
    @GetMapping("{userId}")
    public CommonResponse<List<InspectionVO>> getInspection(@PathVariable int userId){
        if(!inspectionService.existInspectionDetailUser(userId)){
            logger.error("该用户没有分配巡检任务");
            return CommonResponse.createForError("该用户没有分配巡检任务");
        }

        List<InspectionVO> inspectionList = inspectionService.getInspection(userId);
        if(inspectionList == null || inspectionList.isEmpty()){
            logger.error("查看分配巡检任务失败");
            return CommonResponse.createForError("查看分配巡检任务失败");
        }
        logger.info("查看分配巡检任务成功");
        return CommonResponse.createForSuccess("查看分配巡检任务成功", inspectionList);
    }

    /**
     * 查看分配的巡检任务详情
     */
    @GetMapping("/detail/{inspectionWorkId}/{userId}")
    public CommonResponse<List<InspectionDetailVO>> getInspectionDetail(@PathVariable int inspectionWorkId, @PathVariable int userId){
        List<InspectionDetailVO> inspectionDetailVOList = inspectionService.getInspectionDetail(inspectionWorkId, userId);
        if(inspectionDetailVOList.isEmpty()){
            logger.error("查看分配巡检任务失败");
            return CommonResponse.createForError("查看分配巡检任务失败");
        }
        logger.info("查看分配巡检任务成功");
        return CommonResponse.createForSuccess("查看分配巡检任务成功", inspectionDetailVOList);
    }

    /**
     * 修改巡检任务模板
     */
    @PutMapping("/template/{inspectionId}")
    public CommonResponse<Inspection> changeInspection(@PathVariable int inspectionId, @RequestBody Inspection inspection){
        int  inspectionMapId = inspection.getInspectionMapId();
        String inspectionName = inspection.getInspectionName();
        int inspectionUserId = inspection.getInspectionUserId();
        int inspectionClassId = inspection.getInspectionClassId();

        //先判断巡检任务是否存在
        if (!inspectionService.existInspection(inspectionId)) {
            logger.error("巡检任务模板不存在");
            return CommonResponse.createForError("巡检任务模板不存在");
        }

        if(inspectionService.existInspectionName(inspectionName)){
            logger.error("巡检任务名已存在");
            return CommonResponse.createForError("巡检任务名已存在");
        }

        Inspection inspection1 = inspectionService.changeInspection(inspectionId, inspectionMapId, inspectionName, inspectionUserId, inspectionClassId);
        if(inspection1 == null){
            logger.error("修改巡检任务模板失败");
            return CommonResponse.createForError("ERROR");
        }
        logger.info("修改巡检任务模板成功");
        return CommonResponse.createForSuccess("SUCCESS", inspection1);
    }

    /**
     * 修改巡检任务数据
     */
    @PutMapping("/data/{inspectionDataId}")
    public CommonResponse<InspectionData> changeInspectionData(@PathVariable int inspectionDataId, @RequestBody InspectionData inspectionData){
        int inspectionId = inspectionData.getInspectionId();
        int inspectionGroupId = inspectionData.getInspectionGroupId();
        int mapDetailId = inspectionData.getMapDetailId();
        String inspectionDataDesc = inspectionData.getInspectionDataDesc();
        String inspectionDataName = inspectionData.getInspectionDataName();

        //先判断巡检任务数据是否存在
        if (!inspectionService.existInspectionData(inspectionDataId)) {
            logger.error("巡检任务数据不存在");
            return CommonResponse.createForError("巡检任务数据不存在");
        }

        InspectionData inspectionData1 = inspectionService.changeInspectionData(inspectionDataId, inspectionId,
                inspectionGroupId, mapDetailId, inspectionDataDesc, inspectionDataName);
        if(inspectionData1 == null){
            logger.error("修改巡检任务数据失败");
            return CommonResponse.createForError("ERROR");
        }
        logger.info("修改巡检任务数据成功");
        return CommonResponse.createForSuccess("SUCCESS", inspectionData1);
    }

    /**
     * 删除巡检任务模板,把所有分配了巡检模版任务的地方，变成-1
     */
    @DeleteMapping("/template/{inspectionId}")
    public CommonResponse<Object> deleteInspection(@PathVariable int inspectionId){
        //先判断巡检任务是否存在
        if (!inspectionService.existInspection(inspectionId)) {
            logger.error("巡检任务模板不存在");
            return CommonResponse.createForError("巡检任务模板不存在");
        }

        int rows = inspectionService.deleteInspection(inspectionId);
        if(rows == 0){
            logger.error("删除巡检任务模板失败");
            return CommonResponse.createForError("删除巡检任务模板失败");
        }
        logger.info("删除巡检任务模板成功");
        return CommonResponse.createForSuccess("SUCCESS", null);
    }

    /**
     * 删除分配巡检任务
     */
    @DeleteMapping("/{inspectionWorkId}")
    public CommonResponse<Object> deleteInspectionWork(@PathVariable int inspectionWorkId){
        //先判断巡检任务详情是否存在
        if (!inspectionService.existInspectionWork(inspectionWorkId)) {
            logger.error("该分配巡检任务不存在");
            return CommonResponse.createForError("该分配巡检任务不存在");
        }

        int rows = inspectionService.deleteInspectionWork(inspectionWorkId);
        if(rows == 0){
            logger.error("删除分配巡检任务失败");
            return CommonResponse.createForError("删除分配巡检任务失败");
        }
        logger.info("删除分配巡检任务成功");
        return CommonResponse.createForSuccess("SUCCESS", null);
    }

    /**
     * 查找用户巡查，异常，漏检，不合格数
     */
    @GetMapping("/statusNum")
    public CommonResponse<StatusNumVO> getStatusNum(@RequestParam int userId){
        StatusNumVO statusNumVO = inspectionService.getStatusNumVO(userId);
        //StatusNumVO statusNumVO = cacheService.getOrLoad("userIdStatus:" + userId, id -> inspectionService.getStatusNumVO(id), userId, timeOut, timeUnit);
        if(statusNumVO == null){
            logger.error("查找用户巡查，异常，漏检，不合格数失败");
            return CommonResponse.createForError("查找用户巡查，异常，漏检，不合格数失败");
        }
        logger.info("查找用户巡查，异常，漏检，不合格数成功");
        return CommonResponse.createForSuccess("SUCCESS", statusNumVO);
    }

    /**
     * 本周，本季，本月，本年未巡检数
     */
    @GetMapping("/nonInspection")
    public CommonResponse<NonInspectionVO> getNonInspection(@RequestParam int userId) {
        NonInspectionVO nonInspectionVO = inspectionService.getNonInspection(userId);
        if (nonInspectionVO == null) {
            logger.error("查找用户本周，本季，本月，本年未巡检数失败");
            return CommonResponse.createForError("查找用户本周，本季，本月，本年未巡检数失败");
        }
        logger.info("查找用户本周，本季，本月，本年未巡检数成功");
        return CommonResponse.createForSuccess("SUCCESS", nonInspectionVO);
    }

    /**
     * 提交数据
     */
    @PostMapping("/submit/{inspectionGroupId}/{inspectionDetailId}")
    public CommonResponse<Object> submitInspection(@PathVariable int inspectionGroupId, @PathVariable int inspectionDetailId,
                                                   @RequestParam("imageList") MultipartFile[] images,
                                                   @RequestParam("cheatMsg") MultipartFile cheatMsg,
                                                   @RequestParam("dataListJson") MultipartFile dataListJson) throws IOException {
        // 获取文件内容并转换成字符串
        String rawDataListStr = new String(dataListJson.getBytes());
        String dataListStr = rawDataListStr.replace("\\", "").replace("\"{", "{").replace("}\"", "}");

        // 创建 ObjectMapper 实例
        ObjectMapper objectMapper = new ObjectMapper();

        // 创建 DataListWrapper 实例来封装 dataList
        DataListWrapper dataListWrapper;
        try {
            // 将 JSON 字符串转换为 DataListWrapper 实例
            dataListWrapper = objectMapper.readValue(dataListStr, DataListWrapper.class);
        } catch (IOException e) {
            e.printStackTrace();
            // 处理解析失败的情况
            return CommonResponse.createForError("JSON解析失败");
        }

        // 提取 dataList
        List<TextVO> textVOList = dataListWrapper.getText();

        boolean isAbnormal = dataListWrapper.isAbnormal();

        int rows = inspectionService.submitInspection(inspectionDetailId, inspectionGroupId, textVOList, images, cheatMsg, isAbnormal);
        if(rows == 0){
            logger.error("提交数据失败");
            return CommonResponse.createForError("提交数据失败");
        }
        logger.info("提交数据成功");
        return CommonResponse.createForSuccess("SUCCESS", null);
    }

    /**
     * 取出保存图像（返回图片存在nginx里面的文件的http路径）
     */
    @GetMapping("/pictures/{inspectionDetailId}")
    public CommonResponse<List<String>> getPictures(@PathVariable int inspectionDetailId){
        List<String> imageList = inspectionService.getPictures(inspectionDetailId);
        if(imageList == null || imageList.isEmpty()){
            logger.error("图片列表为空");
            return CommonResponse.createForError("图片列表为空");
        }
        logger.info("查询成功");
        return CommonResponse.createForSuccess("SUCCESS", imageList);
    }

    /**
     * 获取点位数据
     */
    @GetMapping("/detailData/{inspectionGroupId}/{inspectionDetailId}")
    public CommonResponse<List<DataVO>> getDetailData(@PathVariable int inspectionGroupId, @PathVariable int inspectionDetailId){
        List<DataVO> dataVOList = inspectionService.getDetailData(inspectionGroupId, inspectionDetailId);
        if(dataVOList.isEmpty() || dataVOList == null){
            logger.error("未查询到点位数据");
            return CommonResponse.createForError("未查询到点位数据");
        }
        logger.info("查询点位数据成功");
        return CommonResponse.createForSuccess("SUCCESS", dataVOList);
    }

    /**
     * 查看所有用户巡查，异常，漏检，不合格数之和
     */
    @GetMapping("/allStatusNum")
    public CommonResponse<StatusNumVO> getAllStatusNum(@RequestParam int userId){
        if(!inspectionService.isAdmin(userId)){
            logger.error("非管理员，无权限查看");
            return CommonResponse.createForError("非管理员，无权限查看");
        }

        StatusNumVO statusNumVO = inspectionService.getAllStatusNumVO();
        if(statusNumVO == null){
            logger.error("查找用户巡查，异常，漏检，不合格数之和失败");
            return CommonResponse.createForError("查找用户巡查，异常，漏检，不合格数之和失败");
        }
        logger.info("查找用户巡查，异常，漏检，不合格数之和成功");
        return CommonResponse.createForSuccess("SUCCESS", statusNumVO);
    }
}
